<template>
  <div class="flex flex-col h-full">
    <!--    <vxe-card title="" class="w-full" :border="false">-->
    <!--      <AuForm-->
    <!--        ref="formRef"-->
    <!--        :formList="formList"-->
    <!--        :exportBtnFlag="false"-->
    <!--        @submit="search"-->
    <!--      />-->
    <!--    </vxe-card>-->

    <AuTable ref="tableRef" v-bind="gridOption" @actionClick="actionClick">
      <template #topWrap>
        <div class="text-[#242930]">
          <span class="text-[--autata-font-gray-color]"
            >{{ t("formula_detail.model_list") }}：</span
          >
          {{ route.query.name }}
        </div>
      </template>
      <template #status_default="{ row }">
        <el-tag :type="row.publishStatus ? 'success' : 'info'">
          {{
            row.publishStatus
              ? t("formula_detail.status_up")
              : t("formula_detail.status_down")
          }}
        </el-tag>
      </template>
    </AuTable>
    <FormulaDetailModal
      v-model="showDetailModal"
      :rowData="rowData"
      :versionId="versionId"
      @confirm="handleConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { AuForm } from "@/components/AuForm";
import { AuTable } from "@/components/AuTable";
import { ACTION_TYPE, PropDefines } from "@/components/AuTable/type";
import {
  pulperFormulaDel,
  PulperFormulaListProp,
  pulperFormulaGetList,
  pulperFormulaPublish,
  pulperFormulaAdd,
  pulperFormulaUpd
} from "@/api/pulper/formula";

import FormulaDetailModal from "./DetailModal.vue";
import { GetListParamProp } from "@/api/user";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { isArray, useGlobal } from "@pureadmin/utils";
import { pick } from "lodash-unified";
import { TpmFormulaListProp } from "@/api/teaPowder/formula";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

defineOptions({
  name: "FormulaTeaPowderDetail"
});

const emit = defineEmits(["update:showModal"]);
const { proxy } = getCurrentInstance();

// region 页面及组件变量集合
const { $storage } = useGlobal<GlobalPropertiesApi>();
const router = useRouter();
const route = useRoute();

const showUploadModal = ref(false);

const formList = ref([
  {
    type: "input",
    key: "name",
    label: "formula_detail.name",
    labelWidth: "40px",
    placeholder: "formula_detail.name_placeholder"
  },
  {
    type: "select",
    key: "publishStatus",
    label: "formula_detail.status",
    placeholder: "formula_detail.status_placeholder",
    labelKey: "label",
    valueKey: "value",
    emptyValues: [null, undefined],
    options: [
      {
        value: "",
        label: "formula_detail.status_all"
      },
      {
        value: "0",
        label: "formula_detail.status_down"
      },
      {
        value: "1",
        label: "formula_detail.status_up"
      }
    ],
    defaultValue: ""
  }
]);

const showDetailModal = ref(false);
const gridOption = reactive<PropDefines>({
  isServerPage: false,
  showCheckbox: true,
  showExportBtn: false,
  columns: [
    // { field: "formulaId", title: "配方编码" },
    { field: "specName", title: "formula_detail.mode_one" },
    { field: "times", title: "formula_detail.times" },
    { field: "level", title: "formula_detail.level" }
    // {
    //   field: "publishStatus",
    //   title: "状态",
    //   slots: { default: "status_default" }
    // },
    // { field: "updateTime", title: "更新时间", width: 190 }
  ],
  actions: [ACTION_TYPE.TADD, ACTION_TYPE.EDIT, ACTION_TYPE.TDELETE],
  operateTools: [],
  topTools: [
    {
      name: "table.refresh",
      key: "refresh"
    }
  ],
  dataSource: []
  // fetchConfig: {
  //   query: {
  //     service: (
  //       params: GetListParamProp<{ version: string; filter: object }>
  //     ) => {
  //       const { start_page, size, ...rest } = params;
  //       params = {
  //         start_page: start_page ?? 1,
  //         size: size ?? 0,
  //         filter: rest
  //       };
  //
  //       return pulperFormulaGetList(params);
  //     },
  //     param: () => {
  //       return {
  //         version: Number(route.query["id"]),
  //         ...formRef.value.getFormData()
  //       };
  //     }
  //   }
  // }
});
const rowData = ref({});
const versionId = ref(route.query["id"] as string);
const tableData = ref([]);

const formRef = ref();
const tableRef = ref();
// endregion

// region 页面公共方法集合

const multiDelete = () => {
  if (!tableRef.value.getCheckboxRecords().length) {
    ElMessage({
      message: t("formula_detail.select_delete_model"),
      type: "warning"
    });
    return;
  }
  proxy.$auMessageBox
    .confirm(t("formula_detail.delete_confirm_model"), t("notice.title"), {
      type: "error"
    })
    .then(() => {
      const ids = tableRef.value.getCheckboxRecords().map(v => v.specId);
      let specs = tableData.value[0].specs;
      specs = specs.filter(v => !ids.includes(v.specId));
      updateFetch(specs);
      // pulperFormulaDel({ ids }).then(res => {
      //   ElMessage({
      //     message: "删除成功",
      //     type: "success"
      //   });
      //   search();
      // });
    });
};

const getDataSource = async () => {
  const params = {
    start_page: 1,
    size: 0,
    filter: {
      versionId: versionId.value
    }
    // filter: formRef.value.getFormData()
  };
  const res = await pulperFormulaGetList(params);
  tableData.value = res.data;
  try {
    // tData = JSON.parse(tableData.value[0].specs);
    const specs = tableData.value[0].specs;
    if (specs.length) {
      gridOption.dataSource = specs.map(v => {
        return {
          ...v,
          ...JSON.parse(v.details)
        };
      });
    }
  } catch (error) {
    console.log(error);
    gridOption.dataSource = [];
  }
};
// endregion

// region 页面及组件事件集合

const search = () => {
  // console.log(data);
  // tableRef.value.refresh();
  getDataSource();
};

const actionClick = ({
  key,
  row
}: {
  key: ACTION_TYPE | string;
  row: PulperFormulaListProp;
}) => {
  switch (key) {
    case ACTION_TYPE.TADD:
    case ACTION_TYPE.EDIT:
      rowData.value = row;
      showDetailModal.value = true;
      break;
    case ACTION_TYPE.TDELETE:
      multiDelete();
      break;
    case ACTION_TYPE.UPLOAD:
      console.log("打开配方导入页面");
      showUploadModal.value = true;
      break;
    case ACTION_TYPE.DOWNLOAD:
      break;
    default:
      break;
  }
};

const handleConfirm = async (data: any) => {
  console.log(data);
  const firstData = tableData.value[0];
  let specs = [];
  if (data.specId) {
    specs = firstData.specs.map(v => {
      if (v.specId == data.specId) {
        const pickData = pick(data, [
          "id",
          "specId",
          "formulaSubid",
          "specName"
        ]);
        return {
          ...pickData,
          details: JSON.stringify({ times: data.times, level: data.level })
        };
      }
      return v;
    });
  } else {
    const last = isArray(firstData.specs)
      ? firstData.specs[firstData.specs.length - 1]
      : { specId: 0 };
    const specId = Number(last.specId) + 1;
    const spec = {
      specId,
      specName: `模式${specId}`,
      details: JSON.stringify({ times: data.times, level: data.level })
    };
    specs = [...(firstData.specs ?? []), spec];
  }
  await updateFetch(specs);
};

const updateFetch = async (specs: any[]) => {
  const firstData = tableData.value[0];
  const param = {
    moduleFormula: {
      ...pick(firstData, [
        "id",
        "formulaId",
        "formulaSubid",
        "versionId",
        "name"
      ])
    },
    specs
  };
  const res = await pulperFormulaUpd(param);
  if (res.code === 200) {
    ElMessage({
      message: t("notice.operation_success"),
      type: "success"
    });
    search();
  }
};

const initFormulaList = async () => {
  await getDataSource();
  if (tableData.value.length) return;
  const modelList = [
    // "模式一",
    // "模式二",
    // "模式三",
    // "模式四",
    // "模式五",
    // "模式六"
  ];
  const param = {
    moduleFormula: {
      versionId: versionId.value,
      name: "",
      note: "",
      publishStatus: 1
    },
    specs: modelList.map((v, i) => {
      return {
        specId: i + 1,
        specName: v,
        details: JSON.stringify({ times: "", level: "" })
      };
    })
  };
  const res = await pulperFormulaAdd(param);
  if (res.code === 200) {
    search();
  }
};
// endregion

onMounted(() => {
  initFormulaList();
});
</script>
